package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.mallcai.bigdata.ladon.client.vo.ReportDataVO;
import com.mallcai.bigdata.ladon.config.props.SystemProperties;
import com.mallcai.bigdata.ladon.datasource.RunInfoResult;
import com.mallcai.bigdata.ladon.dpl.entity.common.Datasource;
import com.mallcai.bigdata.ladon.dpl.entity.report.Report;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import com.mallcai.bigdata.ladon.service.system.IEnvService;
import com.mallcai.bigdata.ladon.tools.dingtalk.DingTalkUtil;
import com.mallcai.bigdata.ladon.tools.dingtalk.Message;
import com.mallcai.bigdata.ladon.utils.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-20 13:06
 */
@Slf4j
@Service
@Order(1950)
public class SendErrorAlarmPostHandler extends AbstractReportQueryPostHandler {


    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private IEnvService iEnvService;

    @Override
    protected void postInternal(ReportQueryContext context) {
        // 只有线上环境才需要发送告警
        if(!iEnvService.isProduct()){
            return;
        }

        RunInfoResult<ReportDataVO> result = context.getResult();
        Exception error = result.getError();
        if (error == null || error instanceof BusinessException){
            return;
        }
        DingTalkUtil.send(systemProperties.getAlertRobot(), buildErrorMessage(context,error));
    }

    private Message buildErrorMessage(ReportQueryContext context, Exception error) {
        Datasource datasource = context.getDatasource();

        Report report = context.getReport();

        return new Message(String.format(MESSAGE_PATTERN,report.getName(), report.getCode(),datasource.getJdbcUrl(), ExceptionUtils.getSimpleMessage(error)));
    }


    private static final String MESSAGE_PATTERN = "报表[名称:%s,编码:%s]查询出错,\n使用的数据源为:[%s],\n错误信息为:%s";


}
